home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / Miro_Downloader.exe / codecs.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-11-12  |  30.6 KB  |  992 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. ''' codecs -- Python Codec Registry, API and helpers.
  5.  
  6.  
  7. Written by Marc-Andre Lemburg (mal@lemburg.com).
  8.  
  9. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  10.  
  11. '''
  12. import __builtin__
  13. import sys
  14.  
  15. try:
  16.     from _codecs import *
  17. except ImportError:
  18.     why = None
  19.     raise SystemError('Failed to load the builtin codecs: %s' % why)
  20.  
  21. __all__ = [
  22.     'register',
  23.     'lookup',
  24.     'open',
  25.     'EncodedFile',
  26.     'BOM',
  27.     'BOM_BE',
  28.     'BOM_LE',
  29.     'BOM32_BE',
  30.     'BOM32_LE',
  31.     'BOM64_BE',
  32.     'BOM64_LE',
  33.     'BOM_UTF8',
  34.     'BOM_UTF16',
  35.     'BOM_UTF16_LE',
  36.     'BOM_UTF16_BE',
  37.     'BOM_UTF32',
  38.     'BOM_UTF32_LE',
  39.     'BOM_UTF32_BE',
  40.     'strict_errors',
  41.     'ignore_errors',
  42.     'replace_errors',
  43.     'xmlcharrefreplace_errors',
  44.     'register_error',
  45.     'lookup_error']
  46. BOM_UTF8 = '\xef\xbb\xbf'
  47. BOM_LE = BOM_UTF16_LE = '\xff\xfe'
  48. BOM_BE = BOM_UTF16_BE = '\xfe\xff'
  49. BOM_UTF32_LE = '\xff\xfe\x00\x00'
  50. BOM_UTF32_BE = '\x00\x00\xfe\xff'
  51. if sys.byteorder == 'little':
  52.     BOM = BOM_UTF16 = BOM_UTF16_LE
  53.     BOM_UTF32 = BOM_UTF32_LE
  54. else:
  55.     BOM = BOM_UTF16 = BOM_UTF16_BE
  56.     BOM_UTF32 = BOM_UTF32_BE
  57. BOM32_LE = BOM_UTF16_LE
  58. BOM32_BE = BOM_UTF16_BE
  59. BOM64_LE = BOM_UTF32_LE
  60. BOM64_BE = BOM_UTF32_BE
  61.  
  62. class CodecInfo(tuple):
  63.     
  64.     def __new__(cls, encode, decode, streamreader = None, streamwriter = None, incrementalencoder = None, incrementaldecoder = None, name = None):
  65.         self = tuple.__new__(cls, (encode, decode, streamreader, streamwriter))
  66.         self.name = name
  67.         self.encode = encode
  68.         self.decode = decode
  69.         self.incrementalencoder = incrementalencoder
  70.         self.incrementaldecoder = incrementaldecoder
  71.         self.streamwriter = streamwriter
  72.         self.streamreader = streamreader
  73.         return self
  74.  
  75.     
  76.     def __repr__(self):
  77.         return '<%s.%s object for encoding %s at 0x%x>' % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
  78.  
  79.  
  80.  
  81. class Codec:
  82.     """ Defines the interface for stateless encoders/decoders.
  83.  
  84.         The .encode()/.decode() methods may use different error
  85.         handling schemes by providing the errors argument. These
  86.         string values are predefined:
  87.  
  88.          'strict' - raise a ValueError error (or a subclass)
  89.          'ignore' - ignore the character and continue with the next
  90.          'replace' - replace with a suitable replacement character;
  91.                     Python will use the official U+FFFD REPLACEMENT
  92.                     CHARACTER for the builtin Unicode codecs on
  93.                     decoding and '?' on encoding.
  94.          'xmlcharrefreplace' - Replace with the appropriate XML
  95.                                character reference (only for encoding).
  96.          'backslashreplace'  - Replace with backslashed escape sequences
  97.                                (only for encoding).
  98.  
  99.         The set of allowed values can be extended via register_error.
  100.  
  101.     """
  102.     
  103.     def encode(self, input, errors = 'strict'):
  104.         """ Encodes the object input and returns a tuple (output
  105.             object, length consumed).
  106.  
  107.             errors defines the error handling to apply. It defaults to
  108.             'strict' handling.
  109.  
  110.             The method may not store state in the Codec instance. Use
  111.             StreamCodec for codecs which have to keep state in order to
  112.             make encoding/decoding efficient.
  113.  
  114.             The encoder must be able to handle zero length input and
  115.             return an empty object of the output object type in this
  116.             situation.
  117.  
  118.         """
  119.         raise NotImplementedError
  120.  
  121.     
  122.     def decode(self, input, errors = 'strict'):
  123.         """ Decodes the object input and returns a tuple (output
  124.             object, length consumed).
  125.  
  126.             input must be an object which provides the bf_getreadbuf
  127.             buffer slot. Python strings, buffer objects and memory
  128.             mapped files are examples of objects providing this slot.
  129.  
  130.             errors defines the error handling to apply. It defaults to
  131.             'strict' handling.
  132.  
  133.             The method may not store state in the Codec instance. Use
  134.             StreamCodec for codecs which have to keep state in order to
  135.             make encoding/decoding efficient.
  136.  
  137.             The decoder must be able to handle zero length input and
  138.             return an empty object of the output object type in this
  139.             situation.
  140.  
  141.         """
  142.         raise NotImplementedError
  143.  
  144.  
  145.  
  146. class IncrementalEncoder(object):
  147.     '''
  148.     An IncrementalEncoder encodes an input in multiple steps. The input can be
  149.     passed piece by piece to the encode() method. The IncrementalEncoder remembers
  150.     the state of the Encoding process between calls to encode().
  151.     '''
  152.     
  153.     def __init__(self, errors = 'strict'):
  154.         '''
  155.         Creates an IncrementalEncoder instance.
  156.  
  157.         The IncrementalEncoder may use different error handling schemes by
  158.         providing the errors keyword argument. See the module docstring
  159.         for a list of possible values.
  160.         '''
  161.         self.errors = errors
  162.         self.buffer = ''
  163.  
  164.     
  165.     def encode(self, input, final = False):
  166.         '''
  167.         Encodes input and returns the resulting object.
  168.         '''
  169.         raise NotImplementedError
  170.  
  171.     
  172.     def reset(self):
  173.         '''
  174.         Resets the encoder to the initial state.
  175.         '''
  176.         pass
  177.  
  178.  
  179.  
  180. class BufferedIncrementalEncoder(IncrementalEncoder):
  181.     '''
  182.     This subclass of IncrementalEncoder can be used as the baseclass for an
  183.     incremental encoder if the encoder must keep some of the output in a
  184.     buffer between calls to encode().
  185.     '''
  186.     
  187.     def __init__(self, errors = 'strict'):
  188.         IncrementalEncoder.__init__(self, errors)
  189.         self.buffer = ''
  190.  
  191.     
  192.     def _buffer_encode(self, input, errors, final):
  193.         raise NotImplementedError
  194.  
  195.     
  196.     def encode(self, input, final = False):
  197.         data = self.buffer + input
  198.         (result, consumed) = self._buffer_encode(data, self.errors, final)
  199.         self.buffer = data[consumed:]
  200.         return result
  201.  
  202.     
  203.     def reset(self):
  204.         IncrementalEncoder.reset(self)
  205.         self.buffer = ''
  206.  
  207.  
  208.  
  209. class IncrementalDecoder(object):
  210.     '''
  211.     An IncrementalDecoder decodes an input in multiple steps. The input can be
  212.     passed piece by piece to the decode() method. The IncrementalDecoder
  213.     remembers the state of the decoding process between calls to decode().
  214.     '''
  215.     
  216.     def __init__(self, errors = 'strict'):
  217.         '''
  218.         Creates a IncrementalDecoder instance.
  219.  
  220.         The IncrementalDecoder may use different error handling schemes by
  221.         providing the errors keyword argument. See the module docstring
  222.         for a list of possible values.
  223.         '''
  224.         self.errors = errors
  225.  
  226.     
  227.     def decode(self, input, final = False):
  228.         '''
  229.         Decodes input and returns the resulting object.
  230.         '''
  231.         raise NotImplementedError
  232.  
  233.     
  234.     def reset(self):
  235.         '''
  236.         Resets the decoder to the initial state.
  237.         '''
  238.         pass
  239.  
  240.  
  241.  
  242. class BufferedIncrementalDecoder(IncrementalDecoder):
  243.     '''
  244.     This subclass of IncrementalDecoder can be used as the baseclass for an
  245.     incremental decoder if the decoder must be able to handle incomplete byte
  246.     sequences.
  247.     '''
  248.     
  249.     def __init__(self, errors = 'strict'):
  250.         IncrementalDecoder.__init__(self, errors)
  251.         self.buffer = ''
  252.  
  253.     
  254.     def _buffer_decode(self, input, errors, final):
  255.         raise NotImplementedError
  256.  
  257.     
  258.     def decode(self, input, final = False):
  259.         data = self.buffer + input
  260.         (result, consumed) = self._buffer_decode(data, self.errors, final)
  261.         self.buffer = data[consumed:]
  262.         return result
  263.  
  264.     
  265.     def reset(self):
  266.         IncrementalDecoder.reset(self)
  267.         self.buffer = ''
  268.  
  269.  
  270.  
  271. class StreamWriter(Codec):
  272.     
  273.     def __init__(self, stream, errors = 'strict'):
  274.         """ Creates a StreamWriter instance.
  275.  
  276.             stream must be a file-like object open for writing
  277.             (binary) data.
  278.  
  279.             The StreamWriter may use different error handling
  280.             schemes by providing the errors keyword argument. These
  281.             parameters are predefined:
  282.  
  283.              'strict' - raise a ValueError (or a subclass)
  284.              'ignore' - ignore the character and continue with the next
  285.              'replace'- replace with a suitable replacement character
  286.              'xmlcharrefreplace' - Replace with the appropriate XML
  287.                                    character reference.
  288.              'backslashreplace'  - Replace with backslashed escape
  289.                                    sequences (only for encoding).
  290.  
  291.             The set of allowed parameter values can be extended via
  292.             register_error.
  293.         """
  294.         self.stream = stream
  295.         self.errors = errors
  296.  
  297.     
  298.     def write(self, object):
  299.         """ Writes the object's contents encoded to self.stream.
  300.         """
  301.         (data, consumed) = self.encode(object, self.errors)
  302.         self.stream.write(data)
  303.  
  304.     
  305.     def writelines(self, list):
  306.         ''' Writes the concatenated list of strings to the stream
  307.             using .write().
  308.         '''
  309.         self.write(''.join(list))
  310.  
  311.     
  312.     def reset(self):
  313.         ''' Flushes and resets the codec buffers used for keeping state.
  314.  
  315.             Calling this method should ensure that the data on the
  316.             output is put into a clean state, that allows appending
  317.             of new fresh data without having to rescan the whole
  318.             stream to recover state.
  319.  
  320.         '''
  321.         pass
  322.  
  323.     
  324.     def __getattr__(self, name, getattr = getattr):
  325.         ''' Inherit all other methods from the underlying stream.
  326.         '''
  327.         return getattr(self.stream, name)
  328.  
  329.  
  330.  
  331. class StreamReader(Codec):
  332.     
  333.     def __init__(self, stream, errors = 'strict'):
  334.         """ Creates a StreamReader instance.
  335.  
  336.             stream must be a file-like object open for reading
  337.             (binary) data.
  338.  
  339.             The StreamReader may use different error handling
  340.             schemes by providing the errors keyword argument. These
  341.             parameters are predefined:
  342.  
  343.              'strict' - raise a ValueError (or a subclass)
  344.              'ignore' - ignore the character and continue with the next
  345.              'replace'- replace with a suitable replacement character;
  346.  
  347.             The set of allowed parameter values can be extended via
  348.             register_error.
  349.         """
  350.         self.stream = stream
  351.         self.errors = errors
  352.         self.bytebuffer = ''
  353.         self.charbuffer = ''
  354.         self.linebuffer = None
  355.  
  356.     
  357.     def decode(self, input, errors = 'strict'):
  358.         raise NotImplementedError
  359.  
  360.     
  361.     def read(self, size = -1, chars = -1, firstline = False):
  362.         ''' Decodes data from the stream self.stream and returns the
  363.             resulting object.
  364.  
  365.             chars indicates the number of characters to read from the
  366.             stream. read() will never return more than chars
  367.             characters, but it might return less, if there are not enough
  368.             characters available.
  369.  
  370.             size indicates the approximate maximum number of bytes to
  371.             read from the stream for decoding purposes. The decoder
  372.             can modify this setting as appropriate. The default value
  373.             -1 indicates to read and decode as much as possible.  size
  374.             is intended to prevent having to decode huge files in one
  375.             step.
  376.  
  377.             If firstline is true, and a UnicodeDecodeError happens
  378.             after the first line terminator in the input only the first line
  379.             will be returned, the rest of the input will be kept until the
  380.             next call to read().
  381.  
  382.             The method should use a greedy read strategy meaning that
  383.             it should read as much data as is allowed within the
  384.             definition of the encoding and the given size, e.g.  if
  385.             optional encoding endings or state markers are available
  386.             on the stream, these should be read too.
  387.         '''
  388.         if self.linebuffer:
  389.             self.charbuffer = ''.join(self.linebuffer)
  390.             self.linebuffer = None
  391.         
  392.         while True:
  393.             if chars < 0:
  394.                 if size < 0:
  395.                     if self.charbuffer:
  396.                         break
  397.                     
  398.                 elif len(self.charbuffer) >= size:
  399.                     break
  400.                 
  401.             elif len(self.charbuffer) >= chars:
  402.                 break
  403.             
  404.             if size < 0:
  405.                 newdata = self.stream.read()
  406.             else:
  407.                 newdata = self.stream.read(size)
  408.             data = self.bytebuffer + newdata
  409.             
  410.             try:
  411.                 (newchars, decodedbytes) = self.decode(data, self.errors)
  412.             except UnicodeDecodeError:
  413.                 exc = None
  414.                 if firstline:
  415.                     (newchars, decodedbytes) = self.decode(data[:exc.start], self.errors)
  416.                     lines = newchars.splitlines(True)
  417.                     if len(lines) <= 1:
  418.                         raise 
  419.                     
  420.                 else:
  421.                     raise 
  422.             except:
  423.                 firstline
  424.  
  425.             self.bytebuffer = data[decodedbytes:]
  426.             self.charbuffer += newchars
  427.             if not newdata:
  428.                 break
  429.                 continue
  430.             self
  431.         if chars < 0:
  432.             result = self.charbuffer
  433.             self.charbuffer = ''
  434.         else:
  435.             result = self.charbuffer[:chars]
  436.             self.charbuffer = self.charbuffer[chars:]
  437.         return result
  438.  
  439.     
  440.     def readline(self, size = None, keepends = True):
  441.         ''' Read one line from the input stream and return the
  442.             decoded data.
  443.  
  444.             size, if given, is passed as size argument to the
  445.             read() method.
  446.  
  447.         '''
  448.         if self.linebuffer:
  449.             line = self.linebuffer[0]
  450.             del self.linebuffer[0]
  451.             if len(self.linebuffer) == 1:
  452.                 self.charbuffer = self.linebuffer[0]
  453.                 self.linebuffer = None
  454.             
  455.             if not keepends:
  456.                 line = line.splitlines(False)[0]
  457.             
  458.             return line
  459.         
  460.         if not size:
  461.             pass
  462.         readsize = 72
  463.         line = ''
  464.         while True:
  465.             data = self.read(readsize, firstline = True)
  466.             if data:
  467.                 if data.endswith('\r'):
  468.                     data += self.read(size = 1, chars = 1)
  469.                 
  470.             
  471.             line += data
  472.             lines = line.splitlines(True)
  473.             if lines:
  474.                 if len(lines) > 1:
  475.                     line = lines[0]
  476.                     del lines[0]
  477.                     if len(lines) > 1:
  478.                         lines[-1] += self.charbuffer
  479.                         self.linebuffer = lines
  480.                         self.charbuffer = None
  481.                     else:
  482.                         self.charbuffer = lines[0] + self.charbuffer
  483.                     if not keepends:
  484.                         line = line.splitlines(False)[0]
  485.                     
  486.                     break
  487.                 
  488.                 line0withend = lines[0]
  489.                 line0withoutend = lines[0].splitlines(False)[0]
  490.                 if line0withend != line0withoutend:
  491.                     self.charbuffer = ''.join(lines[1:]) + self.charbuffer
  492.                     if keepends:
  493.                         line = line0withend
  494.                     else:
  495.                         line = line0withoutend
  496.                     break
  497.                 
  498.             
  499.             if not data or size is not None:
  500.                 if line and not keepends:
  501.                     line = line.splitlines(False)[0]
  502.                 
  503.                 break
  504.             
  505.             if readsize < 8000:
  506.                 readsize *= 2
  507.                 continue
  508.         return line
  509.  
  510.     
  511.     def readlines(self, sizehint = None, keepends = True):
  512.         """ Read all lines available on the input stream
  513.             and return them as list of lines.
  514.  
  515.             Line breaks are implemented using the codec's decoder
  516.             method and are included in the list entries.
  517.  
  518.             sizehint, if given, is ignored since there is no efficient
  519.             way to finding the true end-of-line.
  520.  
  521.         """
  522.         data = self.read()
  523.         return data.splitlines(keepends)
  524.  
  525.     
  526.     def reset(self):
  527.         ''' Resets the codec buffers used for keeping state.
  528.  
  529.             Note that no stream repositioning should take place.
  530.             This method is primarily intended to be able to recover
  531.             from decoding errors.
  532.  
  533.         '''
  534.         self.bytebuffer = ''
  535.         self.charbuffer = u''
  536.         self.linebuffer = None
  537.  
  538.     
  539.     def seek(self, offset, whence = 0):
  540.         """ Set the input stream's current position.
  541.  
  542.             Resets the codec buffers used for keeping state.
  543.         """
  544.         self.reset()
  545.         self.stream.seek(offset, whence)
  546.  
  547.     
  548.     def next(self):
  549.         ''' Return the next decoded line from the input stream.'''
  550.         line = self.readline()
  551.         if line:
  552.             return line
  553.         
  554.         raise StopIteration
  555.  
  556.     
  557.     def __iter__(self):
  558.         return self
  559.  
  560.     
  561.     def __getattr__(self, name, getattr = getattr):
  562.         ''' Inherit all other methods from the underlying stream.
  563.         '''
  564.         return getattr(self.stream, name)
  565.  
  566.  
  567.  
  568. class StreamReaderWriter:
  569.     ''' StreamReaderWriter instances allow wrapping streams which
  570.         work in both read and write modes.
  571.  
  572.         The design is such that one can use the factory functions
  573.         returned by the codec.lookup() function to construct the
  574.         instance.
  575.  
  576.     '''
  577.     encoding = 'unknown'
  578.     
  579.     def __init__(self, stream, Reader, Writer, errors = 'strict'):
  580.         ''' Creates a StreamReaderWriter instance.
  581.  
  582.             stream must be a Stream-like object.
  583.  
  584.             Reader, Writer must be factory functions or classes
  585.             providing the StreamReader, StreamWriter interface resp.
  586.  
  587.             Error handling is done in the same way as defined for the
  588.             StreamWriter/Readers.
  589.  
  590.         '''
  591.         self.stream = stream
  592.         self.reader = Reader(stream, errors)
  593.         self.writer = Writer(stream, errors)
  594.         self.errors = errors
  595.  
  596.     
  597.     def read(self, size = -1):
  598.         return self.reader.read(size)
  599.  
  600.     
  601.     def readline(self, size = None):
  602.         return self.reader.readline(size)
  603.  
  604.     
  605.     def readlines(self, sizehint = None):
  606.         return self.reader.readlines(sizehint)
  607.  
  608.     
  609.     def next(self):
  610.         ''' Return the next decoded line from the input stream.'''
  611.         return self.reader.next()
  612.  
  613.     
  614.     def __iter__(self):
  615.         return self
  616.  
  617.     
  618.     def write(self, data):
  619.         return self.writer.write(data)
  620.  
  621.     
  622.     def writelines(self, list):
  623.         return self.writer.writelines(list)
  624.  
  625.     
  626.     def reset(self):
  627.         self.reader.reset()
  628.         self.writer.reset()
  629.  
  630.     
  631.     def __getattr__(self, name, getattr = getattr):
  632.         ''' Inherit all other methods from the underlying stream.
  633.         '''
  634.         return getattr(self.stream, name)
  635.  
  636.  
  637.  
  638. class StreamRecoder:
  639.     ''' StreamRecoder instances provide a frontend - backend
  640.         view of encoding data.
  641.  
  642.         They use the complete set of APIs returned by the
  643.         codecs.lookup() function to implement their task.
  644.  
  645.         Data written to the stream is first decoded into an
  646.         intermediate format (which is dependent on the given codec
  647.         combination) and then written to the stream using an instance
  648.         of the provided Writer class.
  649.  
  650.         In the other direction, data is read from the stream using a
  651.         Reader instance and then return encoded data to the caller.
  652.  
  653.     '''
  654.     data_encoding = 'unknown'
  655.     file_encoding = 'unknown'
  656.     
  657.     def __init__(self, stream, encode, decode, Reader, Writer, errors = 'strict'):
  658.         ''' Creates a StreamRecoder instance which implements a two-way
  659.             conversion: encode and decode work on the frontend (the
  660.             input to .read() and output of .write()) while
  661.             Reader and Writer work on the backend (reading and
  662.             writing to the stream).
  663.  
  664.             You can use these objects to do transparent direct
  665.             recodings from e.g. latin-1 to utf-8 and back.
  666.  
  667.             stream must be a file-like object.
  668.  
  669.             encode, decode must adhere to the Codec interface, Reader,
  670.             Writer must be factory functions or classes providing the
  671.             StreamReader, StreamWriter interface resp.
  672.  
  673.             encode and decode are needed for the frontend translation,
  674.             Reader and Writer for the backend translation. Unicode is
  675.             used as intermediate encoding.
  676.  
  677.             Error handling is done in the same way as defined for the
  678.             StreamWriter/Readers.
  679.  
  680.         '''
  681.         self.stream = stream
  682.         self.encode = encode
  683.         self.decode = decode
  684.         self.reader = Reader(stream, errors)
  685.         self.writer = Writer(stream, errors)
  686.         self.errors = errors
  687.  
  688.     
  689.     def read(self, size = -1):
  690.         data = self.reader.read(size)
  691.         (data, bytesencoded) = self.encode(data, self.errors)
  692.         return data
  693.  
  694.     
  695.     def readline(self, size = None):
  696.         if size is None:
  697.             data = self.reader.readline()
  698.         else:
  699.             data = self.reader.readline(size)
  700.         (data, bytesencoded) = self.encode(data, self.errors)
  701.         return data
  702.  
  703.     
  704.     def readlines(self, sizehint = None):
  705.         data = self.reader.read()
  706.         (data, bytesencoded) = self.encode(data, self.errors)
  707.         return data.splitlines(1)
  708.  
  709.     
  710.     def next(self):
  711.         ''' Return the next decoded line from the input stream.'''
  712.         data = self.reader.next()
  713.         (data, bytesencoded) = self.encode(data, self.errors)
  714.         return data
  715.  
  716.     
  717.     def __iter__(self):
  718.         return self
  719.  
  720.     
  721.     def write(self, data):
  722.         (data, bytesdecoded) = self.decode(data, self.errors)
  723.         return self.writer.write(data)
  724.  
  725.     
  726.     def writelines(self, list):
  727.         data = ''.join(list)
  728.         (data, bytesdecoded) = self.decode(data, self.errors)
  729.         return self.writer.write(data)
  730.  
  731.     
  732.     def reset(self):
  733.         self.reader.reset()
  734.         self.writer.reset()
  735.  
  736.     
  737.     def __getattr__(self, name, getattr = getattr):
  738.         ''' Inherit all other methods from the underlying stream.
  739.         '''
  740.         return getattr(self.stream, name)
  741.  
  742.  
  743.  
  744. def open(filename, mode = 'rb', encoding = None, errors = 'strict', buffering = 1):
  745.     """ Open an encoded file using the given mode and return
  746.         a wrapped version providing transparent encoding/decoding.
  747.  
  748.         Note: The wrapped version will only accept the object format
  749.         defined by the codecs, i.e. Unicode objects for most builtin
  750.         codecs. Output is also codec dependent and will usually be
  751.         Unicode as well.
  752.  
  753.         Files are always opened in binary mode, even if no binary mode
  754.         was specified. This is done to avoid data loss due to encodings
  755.         using 8-bit values. The default file mode is 'rb' meaning to
  756.         open the file in binary read mode.
  757.  
  758.         encoding specifies the encoding which is to be used for the
  759.         file.
  760.  
  761.         errors may be given to define the error handling. It defaults
  762.         to 'strict' which causes ValueErrors to be raised in case an
  763.         encoding error occurs.
  764.  
  765.         buffering has the same meaning as for the builtin open() API.
  766.         It defaults to line buffered.
  767.  
  768.         The returned wrapped file object provides an extra attribute
  769.         .encoding which allows querying the used encoding. This
  770.         attribute is only available if an encoding was specified as
  771.         parameter.
  772.  
  773.     """
  774.     if encoding is not None and 'b' not in mode:
  775.         mode = mode + 'b'
  776.     
  777.     file = __builtin__.open(filename, mode, buffering)
  778.     if encoding is None:
  779.         return file
  780.     
  781.     info = lookup(encoding)
  782.     srw = StreamReaderWriter(file, info.streamreader, info.streamwriter, errors)
  783.     srw.encoding = encoding
  784.     return srw
  785.  
  786.  
  787. def EncodedFile(file, data_encoding, file_encoding = None, errors = 'strict'):
  788.     """ Return a wrapped version of file which provides transparent
  789.         encoding translation.
  790.  
  791.         Strings written to the wrapped file are interpreted according
  792.         to the given data_encoding and then written to the original
  793.         file as string using file_encoding. The intermediate encoding
  794.         will usually be Unicode but depends on the specified codecs.
  795.  
  796.         Strings are read from the file using file_encoding and then
  797.         passed back to the caller as string using data_encoding.
  798.  
  799.         If file_encoding is not given, it defaults to data_encoding.
  800.  
  801.         errors may be given to define the error handling. It defaults
  802.         to 'strict' which causes ValueErrors to be raised in case an
  803.         encoding error occurs.
  804.  
  805.         The returned wrapped file object provides two extra attributes
  806.         .data_encoding and .file_encoding which reflect the given
  807.         parameters of the same name. The attributes can be used for
  808.         introspection by Python programs.
  809.  
  810.     """
  811.     if file_encoding is None:
  812.         file_encoding = data_encoding
  813.     
  814.     info = lookup(data_encoding)
  815.     sr = StreamRecoder(file, info.encode, info.decode, info.streamreader, info.streamwriter, errors)
  816.     sr.data_encoding = data_encoding
  817.     sr.file_encoding = file_encoding
  818.     return sr
  819.  
  820.  
  821. def getencoder(encoding):
  822.     ''' Lookup up the codec for the given encoding and return
  823.         its encoder function.
  824.  
  825.         Raises a LookupError in case the encoding cannot be found.
  826.  
  827.     '''
  828.     return lookup(encoding).encode
  829.  
  830.  
  831. def getdecoder(encoding):
  832.     ''' Lookup up the codec for the given encoding and return
  833.         its decoder function.
  834.  
  835.         Raises a LookupError in case the encoding cannot be found.
  836.  
  837.     '''
  838.     return lookup(encoding).decode
  839.  
  840.  
  841. def getincrementalencoder(encoding):
  842.     """ Lookup up the codec for the given encoding and return
  843.         its IncrementalEncoder class or factory function.
  844.  
  845.         Raises a LookupError in case the encoding cannot be found
  846.         or the codecs doesn't provide an incremental encoder.
  847.  
  848.     """
  849.     encoder = lookup(encoding).incrementalencoder
  850.     if encoder is None:
  851.         raise LookupError(encoding)
  852.     
  853.     return encoder
  854.  
  855.  
  856. def getincrementaldecoder(encoding):
  857.     """ Lookup up the codec for the given encoding and return
  858.         its IncrementalDecoder class or factory function.
  859.  
  860.         Raises a LookupError in case the encoding cannot be found
  861.         or the codecs doesn't provide an incremental decoder.
  862.  
  863.     """
  864.     decoder = lookup(encoding).incrementaldecoder
  865.     if decoder is None:
  866.         raise LookupError(encoding)
  867.     
  868.     return decoder
  869.  
  870.  
  871. def getreader(encoding):
  872.     ''' Lookup up the codec for the given encoding and return
  873.         its StreamReader class or factory function.
  874.  
  875.         Raises a LookupError in case the encoding cannot be found.
  876.  
  877.     '''
  878.     return lookup(encoding).streamreader
  879.  
  880.  
  881. def getwriter(encoding):
  882.     ''' Lookup up the codec for the given encoding and return
  883.         its StreamWriter class or factory function.
  884.  
  885.         Raises a LookupError in case the encoding cannot be found.
  886.  
  887.     '''
  888.     return lookup(encoding).streamwriter
  889.  
  890.  
  891. def iterencode(iterator, encoding, errors = 'strict', **kwargs):
  892.     '''
  893.     Encoding iterator.
  894.  
  895.     Encodes the input strings from the iterator using a IncrementalEncoder.
  896.  
  897.     errors and kwargs are passed through to the IncrementalEncoder
  898.     constructor.
  899.     '''
  900.     encoder = getincrementalencoder(encoding)(errors, **kwargs)
  901.     for input in iterator:
  902.         output = encoder.encode(input)
  903.         if output:
  904.             yield output
  905.             continue
  906.     
  907.     output = encoder.encode('', True)
  908.     if output:
  909.         yield output
  910.     
  911.  
  912.  
  913. def iterdecode(iterator, encoding, errors = 'strict', **kwargs):
  914.     '''
  915.     Decoding iterator.
  916.  
  917.     Decodes the input strings from the iterator using a IncrementalDecoder.
  918.  
  919.     errors and kwargs are passed through to the IncrementalDecoder
  920.     constructor.
  921.     '''
  922.     decoder = getincrementaldecoder(encoding)(errors, **kwargs)
  923.     for input in iterator:
  924.         output = decoder.decode(input)
  925.         if output:
  926.             yield output
  927.             continue
  928.     
  929.     output = decoder.decode('', True)
  930.     if output:
  931.         yield output
  932.     
  933.  
  934.  
  935. def make_identity_dict(rng):
  936.     ''' make_identity_dict(rng) -> dict
  937.  
  938.         Return a dictionary where elements of the rng sequence are
  939.         mapped to themselves.
  940.  
  941.     '''
  942.     res = { }
  943.     for i in rng:
  944.         res[i] = i
  945.     
  946.     return res
  947.  
  948.  
  949. def make_encoding_map(decoding_map):
  950.     ''' Creates an encoding map from a decoding map.
  951.  
  952.         If a target mapping in the decoding map occurs multiple
  953.         times, then that target is mapped to None (undefined mapping),
  954.         causing an exception when encountered by the charmap codec
  955.         during translation.
  956.  
  957.         One example where this happens is cp875.py which decodes
  958.         multiple character to \\u001a.
  959.  
  960.     '''
  961.     m = { }
  962.     for k, v in decoding_map.items():
  963.         if v not in m:
  964.             m[v] = k
  965.             continue
  966.         m[v] = None
  967.     
  968.     return m
  969.  
  970.  
  971. try:
  972.     strict_errors = lookup_error('strict')
  973.     ignore_errors = lookup_error('ignore')
  974.     replace_errors = lookup_error('replace')
  975.     xmlcharrefreplace_errors = lookup_error('xmlcharrefreplace')
  976.     backslashreplace_errors = lookup_error('backslashreplace')
  977. except LookupError:
  978.     strict_errors = None
  979.     ignore_errors = None
  980.     replace_errors = None
  981.     xmlcharrefreplace_errors = None
  982.     backslashreplace_errors = None
  983.  
  984. _false = 0
  985. if _false:
  986.     import encodings
  987.  
  988. if __name__ == '__main__':
  989.     sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
  990.     sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
  991.  
  992.